package com.ruoyi.gateway.filter;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.gateway.config.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 网关鉴权
 *
 * @author ruoyi
 */
@Component
public class AuthFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        CustomizeRequestWrapper requestWrapper = (request instanceof CustomizeRequestWrapper)
                ? (CustomizeRequestWrapper)request : new CustomizeRequestWrapper(request) ;

        String url = requestWrapper.getRequestURI();
        // 跳过不需要验证的路径（白名单）
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            filterChain.doFilter(requestWrapper, response);
            return;
        }
        String token = getToken(requestWrapper);
        if (StringUtils.isEmpty(token)) {
            unauthorizedResponse(requestWrapper,"令牌不能为空");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            unauthorizedResponse(requestWrapper, "令牌已过期或验证不正确！");
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        if (!islogin) {
            unauthorizedResponse(requestWrapper, "登录状态已过期");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            unauthorizedResponse(requestWrapper, "令牌验证失败");
        }

        // 设置用户信息到请求
        addHeader(requestWrapper, SecurityConstants.USER_KEY, userkey);
        addHeader(requestWrapper, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(requestWrapper, SecurityConstants.DETAILS_USERNAME, username);

        // 内部请求来源参数清除
//        removeHeader(mutate, SecurityConstants.FROM_SOURCE);

        filterChain.doFilter(requestWrapper, response);


    }

    private void addHeader(CustomizeRequestWrapper requestWrapper, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        requestWrapper.addHeader(name, valueEncode);
    }

    private void removeHeader(CustomizeRequestWrapper requestWrapper, String name) {

    }

    private void unauthorizedResponse(HttpServletRequest servletRequest , String msg) {
        log.error("[鉴权异常处理]请求路径:{}, 异常原因:{}", servletRequest.getRequestURI(),msg);
        throw new ServiceException(msg);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest servletRequest) {
        String token = servletRequest.getHeader(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }
}